package cn.tedu._04mvcboot03.exception;

import cn.tedu._04mvcboot03.common.response.JsonResult;
import cn.tedu._04mvcboot03.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String defaultMessage = ex.getFieldError().getDefaultMessage();
        log.error(defaultMessage);
        return new JsonResult(StatusCode.VALIDATED_ERROR,defaultMessage);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String message = ex.getMessage();

        return new JsonResult(StatusCode.VALIDATED_ERROR, message);
    }
}
